﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _14_DateGridView
{
    public static class SQLHelper
    {
        //连接数据库的字符串
        public static SqlConnectionStringBuilder stringBuilder;

        static SQLHelper()
        {
            //初始化连接字符串
            stringBuilder = new SqlConnectionStringBuilder();
            //设置连接字符串的属性
            stringBuilder.DataSource = "DS16PLUS";
            //数据库名称
            stringBuilder.InitialCatalog = "TEST5";
            //账号
            stringBuilder.UserID = "sa";
            //密码
            stringBuilder.Password = "123456";
        }

        /// <summary>
        /// 执行SQL语句，查询结构
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static SqlDataReader GetSqlDataReader(string sql)
        {
            //创建连接数据库连接对象
            SqlConnection sqlCon = new SqlConnection(stringBuilder.ToString());
            //创建数据库操作对象
            SqlCommand sqlCmd = new SqlCommand(sql, sqlCon);
            //打开数据库连接
            sqlCon.Open();
            //执行查询，返回一个读取器(查询结果)
            return sqlCmd.ExecuteReader();
        }
        /// <summary>
        /// 执行SQL语句，返回受影响的行数
        /// </summary>
        /// <param name="sql">SQL语句</param>
        /// <returns>多少行受到影响</returns>
        public static int Update(string sql)
        {
            //连接数据库
            using (SqlConnection sqlCon = new SqlConnection(stringBuilder.ToString()))
            {
                //创建数据库操作对象
                using (SqlCommand sqlCommand = new SqlCommand(sql,sqlCon))
                {
                    //打开数据库
                    sqlCon.Open();
                    //执行SQL语句，返回受影响的行数
                    return sqlCommand.ExecuteNonQuery();
                }
            }
        }

    }
}
